package Timer;

import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Timer;
import java.util.concurrent.ArrayBlockingQueue;

public class MyTimer {
    private final PriorityQueue<MyTask> queue = new PriorityQueue<>();
    public final Object lock = new Object();

    public void schedule(Runnable runnable,long time){
        synchronized (lock){
            queue.offer(new MyTask(runnable,time));
            lock.notify();
        }
    }

    public MyTimer(){
        Thread thread = new Thread(()->{

            while (true){
                synchronized (lock){
                    if (queue.isEmpty()){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    MyTask myTask = queue.peek();
                    long curTime = System.currentTimeMillis();
                    if (myTask.time <= curTime){
                        myTask.runnable.run();
                        queue.poll();
                    }else {
                        try {
                            lock.wait(myTask.time - curTime);
                        } catch (InterruptedException e) {

                        }
                    }
                }
            }
        });
        thread.start();
    }
}
